package com.shangyitong.yygh_order.controller;

import com.shangyitong.Result;
import com.shangyitong.yygh.enums.PaymentTypeEnum;
import com.shangyitong.yygh_order.service.PayMentService;
import com.shangyitong.yygh_order.service.WeiXinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeiXinController {

    @Autowired
    private WeiXinService weiXinService;
    @Autowired
    private PayMentService payMentService;

    /**
     * 微信支付接口
     * @param orderId
     * @return
     */
    @GetMapping("/createNative/{orderId}")
    public Result createNative(@PathVariable Long orderId){
        Map map = weiXinService.createNative(orderId);
        return Result.ok(map);
    }

    /**
     * 更新微信支付状态
     * @param orderId
     * @return
     */
    @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable Long orderId){
        Map<String, String> resultMap = weiXinService.queryPayStatus(orderId);
        if (resultMap == null){
            return Result.fail().message("支付出错");
        }
        if ("SUCCESS".equals(resultMap.get("trade_state"))){
            //更改订单状态，处理支付结果
            String out_trade_no = resultMap.get("out_trade_no");
            payMentService.paySuccess(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }

}
